package com.learn.codesourcelearn.spring;

/**
 * @author yekaile
 * @Date 2020/11/12 19:47
 */

public class ProcessorTest {


    private volatile Integer num = 1;

    private final Object lock = new Object();

    private volatile boolean print1IsPrint = false;

    public static void main(String[] args) throws InterruptedException {
        ProcessorTest processorTest = new ProcessorTest();
        Thread thread1=new Thread(processorTest.new Print1());
        Thread thread2=new Thread(processorTest.new Print2());
        thread1.start();
        thread2.start();
    }

    class Print1 implements Runnable {
        @Override
        public void run() {
            for (int i = 0; i < 50; i++) {
                synchronized (lock) {
                    while (print1IsPrint) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println("Print1 " + num++);
                    print1IsPrint = true;
                    lock.notifyAll();
                }
            }

        }
    }

    class Print2 implements Runnable {
        @Override
        public void run() {
            for (int i = 0; i < 50; i++) {
                synchronized (lock) {
                    while (!print1IsPrint) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println("Print2 " + num++);
                    print1IsPrint = false;
                    lock.notifyAll();
                }
            }
        }
    }
}


